import React, { Component } from 'react'
import {
  Form, Button, Table, Pagination, DatePicker,
  Input, Select, Empty, Tag,
} from 'antd'
import moment from 'moment'

import { address } from '@/Utils/apiConfig'
import request from '@/Utils/fecth'
import AuthComponent from '@/components/AuthComponent'

import './index.less'

const Option = Select.Option
const logApi = address.log

@AuthComponent('log')
export default class Log extends Component {
  columns = [
    {
      title: '日志类型',
      dataIndex: 'log_type',
      render: (v) => v || '--',
    },
    {
      title: '操作人',
      dataIndex: 'name',
      render: (v) => v || '--',
    },
    {
      title: '描述',
      dataIndex: 'event_describe',
      render: (v) => v || '--',
      width: '35%',
    },
    {
      title: '结果',
      dataIndex: 'result',
      render: (v) => {
        const item = resultStatus.find(item => item.label === v) || {}
        return <Tag color={item.color}>{item.label || '--'}</Tag>
      },
    },
    {
      title: 'IP地址',
      dataIndex: 'operator_ip',
      render: (v) => v || '--',
    },
    {
      title: '时间',
      dataIndex: 'operation_time',
      render: (v) => v ? moment(v).format('YYYY-MM-DD HH:mm:ss') : '--',
      sorter: true,
    },
  ]

  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      list: [],
      total: 0,
      typeList: [],
    }
    this.searchOption = {
      pageNum: 1,
      pageSize: 10,
    }
  }

  componentDidMount() {
    this.getList()
    this.getLogTypeList()
  }

  getList = async(values = {}) => {
    this.setState({
      loading: true,
    })
    this.searchOption = {
      ...this.searchOption,
      ...values,
    }
    const { status, data = {}} = await request().get(logApi.userLogList, {
      params: {
        ...this.searchOption,
      },
    })
    this.setState({
      loading: false,
    })
    if (status === 200) {
      this.setState({
        list: (data.data || []).map((v, i) => {
          return {
            ...v,
          }
        }),
        total: data.total || 0,
      })
    }
  }

  search = (values) => {
    const { time, logType = '', keyword = '', result = '' } = values || {}
    const [dateFrom, dateTo] = time || []
    if (dateFrom && dateTo) {
      this.searchOption.dateFrom = moment(dateFrom).format('YYYY-MM-DD HH:mm:ss')
      this.searchOption.dateTo = moment(dateTo).format('YYYY-MM-DD HH:mm:ss')
    } else {
      this.searchOption.dateFrom = ''
      this.searchOption.dateTo = ''
    }
    this.searchOption.keyword = keyword
    this.searchOption.logType = logType
    this.searchOption.result = result
    this.searchOption.pageNum = 1
    this.getList()
  }

  /**
   * 重置
   */
  cancelSearch = () => {
    this.searchForm.resetFields()
    this.searchForm.submit()
  }

  onPageChange = (current, pageSize) => {
    const { searchOption } = this
    searchOption.pageNum = current
    searchOption.pageSize = pageSize
    this.getList()
  };

  onTableChange = (pagination, filters, sorter) => {
    const { order = '' } = sorter || {}
    this.searchOption.sort = order === 'ascend' ? 'asc' : order === 'descend' ? 'desc' : ''
    this.searchForm.submit()
  }

  async getLogTypeList() {
    const { status, data } = await request().get(logApi.getLogType)
    if (status === 200) {
      this.setState({
        typeList: (data || []).map(v => v.event_type),
      })
    }
  }

  render() {
    const { list, loading, total, typeList } = this.state
    return <div className="Log">
      <Form ref={c => this.searchForm = c} className="searchForm" layout="inline" onFinish={this.search}>

        <Form.Item label="搜索" name="keyword">
          <Input style={{ width: '280px' }} placeholder="请输入操作人、描述或者ip地址" />
        </Form.Item>
        <Form.Item label="日志类型" name="logType">
          <Select style={{ width: '125px' }} placeholder="请选择">
            {
              typeList.map(v => {
                return <Option key={v} value={v}>{v}</Option>
              })
            }
          </Select>
        </Form.Item>
        <Form.Item label="结果" name="result">
          <Select style={{ width: '125px' }} placeholder="请选择">
            {
              resultStatus.map(v => {
                return <Option key={v.value} value={v.value}>{v.label}</Option>
              })
            }
          </Select>
        </Form.Item>
        <Form.Item label="提交时间" name="time">
          <DatePicker.RangePicker showTime />
        </Form.Item>
        <Form.Item className="mb24">
          <Button type="primary" htmlType="submit">
            查询
          </Button>
        </Form.Item>
        <Form.Item className="mb24">
          <Button onClick={this.cancelSearch}>
            重置
          </Button>
        </Form.Item>
      </Form>

      <div style={{ position: 'relative', zIndex: 1 }}>
        <Table
          columns={this.columns}
          className={list.length ? '' : 'empty-list'}
          dataSource={list}
          rowKey="logId"
          pagination={false}
          onChange={this.onTableChange}
          loading={loading}
        />
        {
          !list.length &&
          <Empty className="mt24" />
        }
      </div>

      <div className="pagination-box mt24">
        {
          list.length > 0 &&
          <Pagination
            current={this.searchOption.pageNum}
            pageSize={this.searchOption.pageSize}
            total={total}
            showTotal={total => `共 ${total} 条数据`}
            showSizeChanger
            onChange={this.onPageChange} />
        }
      </div>
    </div>
  }
}

const resultStatus = [
  {
    label: '成功',
    value: '0',
    color: 'success',
  },
  {
    label: '失败',
    value: '1',
    color: 'error',
  },
]

